<?php

!defined('IN_SYSTEM') && exit('Access denied');

function caddslashes($target) {
    if (is_array($target)) {
        foreach ($target as $key=>$item) {
            $target[$key] = call_user_func(__FUNCTION__,$item);
        }
        return $target;
    } else {
        return addslashes($target);
    }
}
function cstripslashes($target) {
    if (is_array($target)) {
        foreach ($target as $key=>$item) {
            $target[$key] = call_user_func(__FUNCTION__,$item);
        }
        return $target;
    } else {
        return stripslashes($target);
    }
}

function getRequests($array) {
    $arrays = array();
    foreach ($array as $row) {
        $v = str_replace(array(' '),NULL,trim($_POST[$row]));
        if (!empty($v)) {
            $arrays[$row] = $v;
        }
    }
    return $arrays;
}
function toCNcap($data)
{
	 $capnum=array("零","壹","贰","叁","肆","伍","陆","柒","捌","玖");
	 $capdigit=array("","拾","佰","仟");
	 $subdata=explode(".",$data);
	 $yuan=$subdata[0];
	 $j=0;
	 $nonzero=0;
	 for($i=0;$i<strlen($subdata[0]);$i++){
		 if(0==$i){ //确定个位
			 if($subdata[1]){
				 $cncap=(substr($subdata[0],-1,1)!=0)?"元":"元零";
			 }else{
				 $cncap="元";
			 }
		 }
		 //确定万位
		 if(4==$i){
			 $j=0;
			 $nonzero=0;
			 $cncap="万".$cncap;
		 }
		 //确定亿位
		 if(8==$i){
			 $j=0;
			 $nonzero=0;
			 $cncap="亿".$cncap;
		 }
		 $numb=substr($yuan,-1,1); //截取尾数
		 $cncap=($numb)?$capnum[$numb].$capdigit[$j].$cncap:(($nonzero)?"零".$cncap:$cncap);
		 $nonzero=($numb)?1:$nonzero;
		 $yuan=substr($yuan,0,strlen($yuan)-1); //截去尾数
		 $j++;
	 }
	 if($subdata[1]){
		 $chiao=(substr($subdata[1],0,1))?$capnum[substr($subdata[1],0,1)]."角":"零";
		 $cent=(substr($subdata[1],1,1))?$capnum[substr($subdata[1],1,1)]."分":"零分";
	 }
	 $cncap .= $chiao.$cent."整";
	 $cncap=preg_replace("/(零)+/","//1",$cncap); //合并连续"零"
	 return $cncap;
}
function cauthcode($string, $operation = 'DECODE', $key = '', $expiry = 0) {

    $ckey_length = 6;

    $key = md5($key ? $key : AUTH_KEY);
    $keya = md5(substr($key, 0, 16));
    $keyb = md5(substr($key, 16, 16));
    $keyc = $ckey_length ? ($operation == 'DECODE' ? substr($string, 0, $ckey_length): substr(md5(microtime()), -$ckey_length)) : '';

    $cryptkey = $keya.md5($keya.$keyc);
    $key_length = strlen($cryptkey);

    $string = $operation == 'DECODE' ? base64_decode(str_replace(array('xiexian','jiahao'), array('/','+'), substr($string, $ckey_length))) : sprintf('%010d', $expiry ? $expiry + time() : 0).substr(md5($string.$keyb), 0, 16).$string;
    $string_length = strlen($string);

    $result = '';
    $box = range(0, 255);

    $rndkey = array();
    for($i = 0; $i <= 255; $i++) {
        $rndkey[$i] = ord($cryptkey[$i % $key_length]);
    }

    for($j = $i = 0; $i < 256; $i++) {
        $j = ($j + $box[$i] + $rndkey[$i]) % 256;
        $tmp = $box[$i];
        $box[$i] = $box[$j];
        $box[$j] = $tmp;
    }

    for($a = $j = $i = 0; $i < $string_length; $i++) {
        $a = ($a + 1) % 256;
        $j = ($j + $box[$a]) % 256;
        $tmp = $box[$a];
        $box[$a] = $box[$j];
        $box[$j] = $tmp;
        $result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));
    }

    if($operation == 'DECODE') {
        if((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26).$keyb), 0, 16)) {
            return substr($result, 26);
        } else {
            return '';
        }
    } else {
        return $keyc.str_replace(array('=','/','+'), array(NULL,'xiexian','jiahao'), base64_encode($result));
    }

}


/**
 +----------------------------------------------------------
 * 字符串截取，支持中文和其他编码
 +----------------------------------------------------------
 * @static
 * @access public
 +----------------------------------------------------------
 * @param string $str 需要转换的字符串
 * @param string $start 开始位置
 * @param string $length 截取长度
 * @param string $charset 编码格式
 * @param string $suffix 截断显示字符
 +----------------------------------------------------------
 * @return string
 +----------------------------------------------------------
 */
function msubstr($str, $start=0, $length, $charset="utf-8", $suffix=true)
{
if(function_exists("mb_substr")){
            if ($suffix && strlen($str)>$length)
                return mb_substr($str, $start, $length, $charset)."...";
        else
                 return mb_substr($str, $start, $length, $charset);
    }
    elseif(function_exists('iconv_substr')) {
            if ($suffix && strlen($str)>$length)
                return iconv_substr($str,$start,$length,$charset)."...";
        else
                return iconv_substr($str,$start,$length,$charset);
    }
    $re['utf-8']   = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";
    $re['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/";
    $re['gbk']    = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/";
    $re['big5']   = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/";
    preg_match_all($re[$charset], $str, $match);
    $slice = join("",array_slice($match[0], $start, $length));
    if($suffix) return $slice."…";
    return $slice;
}


function utf_substr($str,$len)
{
for($i=0;$i<$len;$i++)
{
$temp_str=substr($str,0,1);
if(ord($temp_str) > 127)
{
$i++;
if($i<$len)
{
$new_str[]=substr($str,0,3);
$str=substr($str,3);
}
}
else
{
$new_str[]=substr($str,0,1);
$str=substr($str,1);
}
}
return join($new_str);
}


function makeOrderId() {
    return date('ymdHis').str_pad(rand(1,9999),4,'0',STR_PAD_LEFT);
}
function orderState($state) {

    return $_ENV['config']['order_state'][$state] ? $_ENV['config']['order_state'][$state] : '未知状态';
}

function template($tpl) {
    $tpl_file_path = __PATH__.'/source/template/'.$tpl.'.htm';
    if(!file_exists($tpl_file_path)) exit($tpl_file_path);
    return $tpl_file_path;
}

function url($app,$module,$args) {
    return "?app={$app}&mod={$module}";
}

function opt($type,$url,$extra='') {
    return '<a href="javascript:;"><img href="'.$url.'" src="./res/image/icon_'.$type.'.gif" '.$extra.'/></a>';
}

function del($type,$url,$extra='')
{
	return '<a href="javascript:;"onclick="if(confirm(\'确定要删除\')) window.location.href =\'' .$url. '\';" ><img src="./res/image/icon_'.$type.'.gif"'.$extra.'/></a>';
}

function yesno($val,$extra='') {
    return '<img src="./res/image/'.($val ? 'yes' : 'no').'.gif" '.$extra.'/>';
}

function showhide($name,$value=null) {
    if (is_array($name)) {
        $html = '';
        foreach ($name as $key=>$value){
            $html .= showhide($key,$value);
        }
        return $html;
    } else {
        return "<input type='hidden' name='{$name}' id='{$name}' value='{$value}' />";
    }
}
function showGetHide() {
    return showhide($_GET);
}

function halt($message) {
    exit($message);
}

function formhash() {
    return substr(md5($_SERVER['HTTP_USER_AGENT'].'cevin&authkey'.substr(time(),0,5)),16);
}

function csetcookie($name,$value=null,$expiry=0) {
    $expiry = ($expiry === 0  ? 0 : ($expiry < 0 ? -3600 : time()+$expiry));
    setcookie($_ENV['config']['cookie']['prefix'].$name,$value,$expiry,'/',$_ENV['config']['cookie']['domain']);
    $_COOKIE[$_ENV['config']['cookie']['prefix'].$name] = $value;
}
function cgetcookie($name) {
    return $_COOKIE[$_ENV['config']['cookie']['prefix'].$name];
}
/*类文件自动引入
(1)/app下业务类
(2)/class下工具类
*/
function import($target) 
{
    // 类(自动)加载
    if (substr($target,-11) == 'ControlPage') 
	{
        $path = __PATH__."/source/app/{$target}.php";
    } 
	elseif(substr($target,0,6) == 'class_') 
	{
        $path = __PATH__."/source/class/{$target}.php";
    }
	else if(substr($target,-6) == 'Entity')
	{
		$path = __PATH__."/source/entity/{$target}.php";
	}
    if (!file_exists($path)) {
        halt('file not found:'.$path);
    }
    include_once $path;
}

function getFastInsertSql($table,$array) {
    $sql_tmp = array();
    foreach($array as $key=>$row) {
        $sql_tmp['key'][] = "`{$key}`";
        $sql_tmp['val'][] = "'{$row}'";
    }

    $sql =  "INSERT INTO `{$table}` (".implode(',',$sql_tmp['key']).") VALUES (".implode(',',$sql_tmp['val']).")";

    return $sql;
}

function debug($object) {
    echo '<pre>'.htmlspecialchars(var_export($object,1)).'</pre>';
}

/****************************
    取出魔法符号
	@param string   字符串
****************************/
function saddslashes($string) {
	if(is_array($string)) {
		foreach($string as $key => $val) {
			$string[$key] = saddslashes($val);
		}
	} else {
		$string = addslashes($string);
	}
	return $string;
}
/**
 * 验证日期格式
 */
function ValidateDate($str)
{
	$flag=true;
    $regex = $pn = '/^((((1[6-9]|[2-9]\d)\d{2})-(0?[13578]|1[02])-(0?[1-9]|[12]\d|3[01]))|(((1[6-9]|[2-9]\d)\d{2})-(0?[13456789]|1[012])-(0?[1-9]|[12]\d|30))|(((1[6-9]|[2-9]\d)\d{2})-0?2-(0?[1-9]|1\d|2[0-8]))|(((1[6-9]|[2-9]\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))-0?2-29))$/';
    if(!preg_match($regex,$str))
    {
     	$flag=false;
    }
    return $flag;
}

/**
 * 验证价格
 */
function ValidatePrice($str)
{
	$flag=true;
    $regex = '/^(\d|[1-9]\d{0,9})(\.\d{1,2})?$/';
    if(!preg_match($regex,$str))
    {
     	$flag=false;
    }
    return $flag;
}

/**
 * 返回POST或GET过来的值
 */
function GetOrPost($var)
{
	$value = '';
	if(isset($_POST[$var])) 
	{
		$value = $_POST[$var];
	} 
	elseif (isset($_GET[$var])) 
	{
		$value = $_GET[$var];
	}
	return $value;
}

/**
 * 验证邮箱格式
 */
function CheckEmail($email) 
{ 
	return eregi("^[0-9a-z][a-z0-9\._-]{1,}@[a-z0-9-]{1,}[a-z0-9]\.[a-z\.]{1,}[a-z]$", $email); 
} 

/*[插入记录]*/
function InsertTable($tablename, $insertsqlarr, $returnid=0, $replace = false, $silent=0) 
{
	$insertkeysql = $insertvaluesql = $comma = '';
	foreach ($insertsqlarr as $insert_key => $insert_value) 
	{
		$insertkeysql .= $comma.'`'.$insert_key.'`';
		$insertvaluesql .= $comma.'\''.$insert_value.'\'';
		$comma = ', ';
	}
	$method = $replace?'REPLACE':'INSERT';
	//writeD($method.' INTO '.$tablename .' ('.$insertkeysql.') VALUES ('.$insertvaluesql.') ', $silent?'SILENT':''); 
	$_ENV['db']->runSql($method.' INTO `'.$tablename .'` ('.$insertkeysql.') VALUES ('.$insertvaluesql.') ', $silent?'SILENT':'');
	return $_ENV['db']->insertId();
}

/*[更新记录]*/
function UpdateTable($tablename, $setsqlarr, $wheresqlarr) 
{
	global $_SGLOBAL;
	$setsql = $comma = '';
	foreach ($setsqlarr as $set_key => $set_value) {
		$setsql .= $comma.$set_key.'=\''.$set_value.'\'';
		$comma = ', ';
	}
	return $_ENV['db']->runSql('UPDATE `'. $tablename .'` SET '.$setsql.' WHERE '.getwheresql($wheresqlarr));
}

function DeteteTable($tableName,$wheresqlarr)
{
	return $_ENV['db']->runSql('Delete from `'. $tableName .'` WHERE '.getwheresql($wheresqlarr));
}

/*[拼where语句]*/
function getwheresql($wheresqlarr) {
	$result = $comma = '';
	if(empty($wheresqlarr)) {
		$result = '1';
	} elseif(is_array($wheresqlarr)) {
		foreach ($wheresqlarr as $key => $value) {
			$result .= $comma.$key.'=\''.$value.'\'';
			$comma = ' AND ';
		}
	} else {
		$result = $wheresqlarr;
	}
	return $result;
}

/*绑定下拉框*/
function BindCombox($name,$id,$datas,$default='')
{
	$str =  '<select name="'.$name.'" id="'.$id.'" >' ;
	$str .= '<option value="">请选择</option>';
	foreach((array)$datas as $key=>$value)
	{
		$str .='<option value="'.$value.'" ';
		if($default && $default==$value)
		{
			$str .=' selected="selected" ';
		}
		$str .='>'.$value.'</option>';
	}
	$str .='</select>';
	return $str;
}
/*绑定下拉框*/
function BindComboxForKey($name,$id,$datas,$default='')
{
	$str =  '<select name="'.$name.'" id="'.$id.'" >' ;
	$str .= '<option value="">请选择</option>';
	foreach((array)$datas as $key=>$value)
	{
		$str .='<option value="'.$key.'" ';
		if($default && $default==$key)
		{
			$str .=' selected="selected" ';
		}
		$str .='>'.$value.'</option>';
	}
	$str .='</select>';
	return $str;
}
/*绑定下拉框*/
function BindComboxs($name,$id,$datas,$v,$t,$default='')
{
	$str =  '<select name="'.$name.'" id="'.$id.'" >' ;
	$str .= '<option value="">请选择</option>';
	foreach((array)$datas as $key=>$value)
	{
		$str .='<option value="'.$value[$v].'" ';
		if($default && $default==$value[$v])
		{
			$str .=' selected="selected" ';
		}
		$str .='>'.$value[$t].'</option>';
	}
	$str .='</select>';
	return $str;
}

function writeD($val)
{
	$body = $val;
	if(is_array($val) && count($val)>0)
	{
		foreach($val as $key=>$value)
		{
			$body.=$key . ':' . $value .'</br>';
		}
	}

    if (!$handle = fopen('./debug.txt', 'a')) 
	{
         echo "不能打开文件 $filename";
         exit;
    }
    if (fwrite($handle, $body) === FALSE) 
	{
        echo "不能写入到文件 $filename";
        exit;
    }
    fclose($handle);
}
	/**
	 * 格式化字符串
	 * @param <type> $str   字符串
	 */
	function FormatStr($str)
	{
		$len =  intval(strlen($str) / 2) * 2 + ((strlen($str) % 2)==0?0:2);	
		$str = str_pad($str,$len,'0',STR_PAD_LEFT);
		$count = intval(strlen($str) /2 );
		$result = '';
		for($i=0;$i<$count;$i++)
		{
			$result.= intval(substr($str,$i*2,2)) . ',';
		}
		return rtrim($result, ",");

	}
	
	/**
     * 分页
	 * (1) 表名
	 * (2) id名称
	 * (3) where条件
     */
	function PrePageByURL($tableName,$idName,$where,$page,$orderName,$url)
	{
		$sql = "SELECT count({$idName}) as total FROM `{$tableName}` WHERE {$where}";
		$total = $_ENV['db']->fetchCol($sql);
		$pager = new class_pager();
		$pager->setConfig($page,$total);
		$pager->setUrl('?'.$url,'tpt');
		$this->view->pager = $pager->output();
		return $_ENV['db']->fetchAll("SELECT * FROM `{$tableName}` WHERE {$where} order by {$orderName} LIMIT ".$pager->getLimit()." OFFSET ".$pager->getOffset());
	}
